<!--
 * @Author: Lizhenyu
 * @Date: 2021-07-12 16:30:58
 * @FilePath: \usp-osm-frondend\src\views\serviceCenter\servicePackage\updatePackage.vue
-->
<template>
  <div
    class="source"
    v-loading="pageLoading"
    :element-loading-text="loadingText"
  >
    <div class="newPageTitle">
      <span class="backIcon" @click="closeDrawer"
        ><i class="el-icon-back"></i
      ></span>
      <h1 v-if="type === 'add'" style="display: inline-block; margin-left: 10px">
        <!-- {{ isAdd ? '新增服务包' : '修改服务包' }} -->
        新增服务包
      </h1>
      <h1 v-else-if="type === 'edit'" style="display: inline-block; margin-left: 10px">
        <!-- {{ isAdd ? '新增服务包' : '修改服务包' }} -->
        修改服务包
      </h1>
      <h1 v-else-if="type === 'detail'" style="display: inline-block; margin-left: 10px">
        <!-- {{ isAdd ? '新增服务包' : '修改服务包' }} -->
        详情
      </h1>
    </div>
    <div class="base-info">
      <h2 class="model-title">基本信息</h2>
      <el-form
        :model="editData"
        :rules="rules"
        label-position="left"
        ref="editLabel"
        label-width="170px"
        size="small"
        class="dialogForm"
      >
        <el-row :gutter="20">
          <el-form-item prop="code" class="formPosition" label="服务包编码">
            <el-input
              type="text"
              v-model="editData.code"
              placeholder="服务包编码"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item prop="name" class="formPosition" label="服务包名称">
            <el-input
              type="text"
              v-model="editData.name"
              :disabled="type === 'detail'"
              @input="editData.name=editData.name.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5]/g,'')"
              placeholder="服务包名称"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item prop="quantity" class="formPosition" label="投放数量">
            <el-input
              type="number"
              :disabled="type === 'detail'"
              v-model="editData.quantity"
              placeholder="不填写时为无限数量"
            ></el-input>
          </el-form-item> -->
          <el-form-item
            prop="periodType"
            class="formPosition"
            label="有效期类型"
          >
            <el-select :disabled="type === 'detail'" v-model="editData.periodType" placeholder="请选择">
              <el-option
                v-for="item in lookupItems.PERIODTYPE"
                :key="item.dicCode"
                :label="item.dicName"
                :value="item.dicCode"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            prop="usePeriodTime"
            class="formPosition"
            label="使用有效期"
            v-if="editData.periodType === '1'"
          >
            <div class="block">
              <el-date-picker
                :disabled="type === 'detail'"
                v-model="editData.usePeriodTime"
                type="daterange"
                range-separator="至"
                :default-value="[new Date(), new Date()]"
                value-format="yyyy-MM-dd"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                @change="changeCreateTime"
                @focus="selectDate"
              ></el-date-picker>
            </div>
          </el-form-item>
          <el-form-item
            prop="periodDay"
            class="formPosition"
            label="有效期天数"
            v-if="editData.periodType === '2'"
          >
          <el-input :disabled="type === 'detail'" type="number" v-model="editData.periodDay" placeholder="有效期天数"></el-input>
          </el-form-item>
          <el-form-item
            prop="isNeedInsurance"
            class="formPosition"
            label="是否需要保险"
          >
            <el-radio-group :disabled="type === 'detail'" v-model="editData.isNeedInsurance">
              <el-radio
                v-for="item in isNeedList"
                :key="item.label"
                :label="item.label"
              >
                {{ item.name }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="service-info">
      <h2 class="model-title">服务信息</h2>
      <el-row :gutter="20">
        <div class="mb-lg">
          <!-- :cell-class-name="otherStyle" -->
          <v-table
            :data="tableData"
            class="service-table"
            ref="multipleTable"
            :listLoading="listLoading"
            :loadingText="loadingText"
            border
            :pagination="false"
            v-on:handleSelectionChange="handleSelectionChange"
          >
            <div slot="header">
              <el-button
                @click="addSerivice"
                icon="el-icon-plus"
                class="dark-btn"
                v-if="type !== 'detail'"
                style="margin-bottom: 0 !important"
              >
                添加服务
              </el-button>
              <el-button
                @click="cancelSerivice"
                icon="el-icon-delete"
                class="dark-btn"
                :disabled="tableData.length < 1 || selectData.length < 1"
                v-if="type !== 'detail'"
                style="margin-bottom: 0 !important"
              >
                取消服务
              </el-button>
            </div>
            <el-table-column type="selection" width="55" :selectable="getSelectAble"> </el-table-column>
            <el-table-column
              label="服务编号"
              align="center"
              min-width="120"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <span>
                  {{ scope.row.code }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              label="服务名称"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                <!-- {{ getDictionaryNameByCode('LABELTYPE', scope.row.packgeType) }} -->
                {{ scope.row.name }}
              </template>
            </el-table-column>
            <el-table-column
              label="服务商"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ scope.row.serviceProviderName }}
              </template>
            </el-table-column>
            <el-table-column
              label="是否绑定券池"
              align="center"
              min-width="110"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ scope.row.isBoundCoupon === '0' ? '否' : '是' }}
              </template>
            </el-table-column>
            <el-table-column
              label="服务类型"
              align="center"
              min-width="100"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope">
                {{ getDictionaryNameByCode('SERVICETYPE', scope.row.type ) }}
              </template>
            </el-table-column>
            <el-table-column
              label="数量"
              align="center"
              min-width="110"
            >
              <template slot-scope="scope">
                <!-- :class="scope.row.isInputQuantity?'':'border-style'" -->
                <el-input
                  type="number"
                  :disabled="type === 'detail'"
                  v-model="scope.row.quantity"
                  @input="scope.row.quantity=scope.row.quantity.replace(/^-|\.|0{2}|[0][1-9]|-[1-9]\d*$/g,'')"
                  placeholder="不填写时为无限数量"
                ></el-input>
                <!-- <span :class="scope.row.isInputQuantity?'validate-show':'validate-style'">请填写数量</span> -->
              </template>
            </el-table-column>
          </v-table>
        </div>
      </el-row>
    </div>
    <div class="footer">
      <div class="footer-btn">
        <el-button v-if="type !== 'detail'" @click="closeDrawer" class="white-btn">取消</el-button>
        <el-button v-if="type !== 'detail'" @click="saveEdit('editLabel')" class="dark-btn">
          保存
        </el-button>
      </div>
    </div>

    <add-service ref="addDialog"></add-service>
  </div>
</template>

<script>
import { xor, cloneDeep } from 'lodash'
import { saveServicePackageEdit, getServicePackageDetail } from '@/api/service'
import addService from './dialog/addService'
import { mapGetters } from 'vuex'
import VTable from '@/components/PageTable/index'
import { common } from '@/mixins/common'
import { setRouterParams, getRouterParams } from '@/utils/auth'
import { timestampToChange } from '@/filters'

export default {
  name: 'updatePackage',
  mixins: [common],
  components: {
    VTable,
    addService
  },
  data () {
    return {
      id: '',
      pageLoading: false,
      listLoading: false,
      isUpdateNum: 0,
      isAdd: true,
      orgId: 1,
      loadingText: '加载中...',
      showNameRequire: false,
      tableData: [],
      selectData: [],
      typeArr: [],
      isNeedList: [
        {
          label: '1',
          name: '是'
        },
        {
          label: '0',
          name: '否'
        }
      ],
      rules: {
        name: [
          {
            required: true,
            message: '服务包名称不能为空'
          }
          // { validator: specialValidate, trigger: 'blur' }
        ],
        periodType: [
          {
            required: true,
            message: '有效期类型不能为空',
            trigger: 'change'
          }
        ],
        isNeedInsurance: [
          {
            required: true,
            message: '请选择其中一项',
            trigger: 'change'
          }
        ],
        usePeriodTime: [
          {
            required: true,
            message: '请选择起始时间',
            trigger: ['blur', 'change']
          }
        ],
        periodDay: [
          {
            required: true,
            message: '请输入有效期天数',
            trigger: 'blur'
          }
        ]
      },
      editData: {
        code: '',
        isNeedInsurance: '',
        name: '',
        usePeriodTime: [],
        periodBeginTime: '',
        periodEndTime: '',
        quantity: '',
        periodType: '',
        status: '',
        responseServicePackageDetailVoList: [],
        periodDay: ''
      },
      // timeData: {
      //   periodBeginTime: '',
      //   periodEndTime: ''
      // },
      isSave: false,
      type: '',
      deleteObjList: [],
      deleteObj: {
        id: '',
        isDeleted: '1'
      }
    }
  },
  created () {
    this.attributeAction(this.$route.params.id)
  },
  mounted () {
    this.getDataChange()
  },
  computed: {
    ...mapGetters(['lookupItems'])
  },
  beforeRouteLeave (to, from, next) {
    if (this.isSave) {
      next()
    } else {
      if (this.isUpdateNum > 1) {
        this.$confirm(this.$t('closeDrawerTip'), '', {
          confirmButtonText: this.$t('confirmYes'),
          cancelButtonText: this.$t('confirmNo')
        })
          .then(() => {
            next()
          })
          .catch(() => {
            next(false)
            this.$setMenuActived(this.$route.path)
          })
      } else {
        next()
      }
    }
  },
  methods: {
    changeCreateTime (val) {
    },
    selectDate () {
    },
    getDataChange () {
      this.isUpdateNum = 0
      /* === 弹窗监听 start ==== */
      this.$watch(
        'editData',
        function () {
          this.isUpdateNum++
        },
        { deep: true }
      )
      /* === 弹窗监听 end ==== */
    },
    handleSelectionChange (val) {
      this.selectData = val
    },
    saveEdit (formName) {
      // 保存新增修改
      const self = this
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let perFlag
          const flagArr = []
          self.tableData.forEach((item, index) => {
            if (item.isBoundCoupon === '1') {
              if (!item.quantity) {
                perFlag = false
              } else {
                perFlag = true
              }
            } else {
              perFlag = true
            }
            flagArr.push(perFlag)
          })
          const flag = flagArr.every(value => {
            return value === true
          })

          if (!flag) {
            this.$alert('请填写数量', {
              confirmbuttontext: '确定'
            })
          }
          self.editData.name = self.editData.name.trim()
          const requestServicePackageDetailVos = []

          if (!this.isAdd) {
            requestServicePackageDetailVos.push(...self.deleteObjList)
          }
          requestServicePackageDetailVos.push(...self.tableData)
          const data = {
            id: self.id,
            code: self.editData.code,
            isNeedInsurance: self.editData.isNeedInsurance,
            name: self.editData.name,
            periodBeginTime: self.editData.usePeriodTime ? new Date(self.editData.usePeriodTime[0] + ' ' + '00:00:00').getTime() : '',
            periodEndTime: self.editData.usePeriodTime ? new Date(self.editData.usePeriodTime[1] + ' ' + '23:59:59').getTime() : '',
            periodType: self.editData.periodType,
            quantity: self.editData.quantity === '' ? null : self.editData.quantity,
            requestServicePackageDetailVos: requestServicePackageDetailVos,
            periodDay: self.editData.periodDay
          }
          if (flag) {
            this.pageLoading = true
            saveServicePackageEdit(data)
              .then((response) => {
                this.pageLoading = false
                // 调用接口保存新增修改attribute
                const data = response
                if (Number(data.code) === 1) {
                  self.$emit('search')
                  self.$alert('数据保存成功', {
                    confirmButtonText: '确定',
                    callback: (action) => {
                      this.$router.push({ name: 'servicePackage' })
                    }
                  })
                  this.isSave = true
                } else {
                  this.$confirm(this.$t(response.code), {
                    confirmButtonText: '确认',
                    showCancelButton: false
                  })
                }
              })
              .catch((error) => {
                this.pageLoading = false
                this.$confirm(error, {
                  confirmbuttontext: this.$t('confirmOK'),
                  showcancelbutton: false
                })
              })
          }
        } else {
          return false
        }
      })
    },
    closeDrawer () {
      this.$router.push({ name: 'servicePackage' })
    },
    attributeAction (id) {
      const name = this.$route.name
      this.type = this.$route.params.type
      if (this.type === 'detail') {
        this.$route.meta.title = '详情'
        this.$route.meta.titlePath = '详情'
      } else if (this.type === 'edit') {
        this.$route.meta.title = '修改服务包'
        this.$route.meta.titlePath = '修改服务包'
      } else if (this.type === 'add') {
        this.$route.meta.title = '新增服务包'
        this.$route.meta.titlePath = '新增服务包'
      }
      if (id) {
        this.id = id
        this.isAdd = false
        setRouterParams(this.$route)
        this.edit(this.id)
      } else {
        if (name === 'editPackage') {
          this.isAdd = false
          const routeParams = getRouterParams(this.$route)
          this.type = routeParams.type
          this.id = routeParams.id
          this.edit(this.id)
        } else {
          this.isAdd = true
          this.type = 'add'
          this.initpage()
        }
      }
    },
    edit (id) {
      const model = { id: id }
      this.pageLoading = true
      getServicePackageDetail(model)
        .then((response) => {
          this.pageLoading = false
          // 编辑Attribute
          const data = response
          if (data) {
            if (Number(data.code) === 1) {
              const obj = data.obj
              const datas = obj
              this.initDate(datas)
            } else if (Number(data.code) === 0) {
              this.$confirm(data.msg, {
                confirmButtonText: '确认',
                showCancelButton: false
              })
            } else {
              this.$alert(this.$t(response.code))
            }
          }
        })
        .catch((_) => {
          this.pageLoading = false
        })
    },
    initpage () {
      // 初始页面值
      this.editData = {
        code: '',
        isNeedInsurance: '',
        name: '',
        usePeriodTime: [],
        periodBeginTime: '',
        periodEndTime: '',
        quantity: '',
        periodType: '',
        status: '',
        responseServicePackageDetailVoList: [],
        periodDay: ''
      }
    },
    initDate (allData) {
      if (allData) {
        this.editData = {
          code: allData.code,
          name: allData.name,
          isNeedInsurance: allData.isNeedInsurance,
          quantity: allData.quantity,
          status: allData.status,
          responseServicePackageDetailVoList: allData.responseServicePackageDetailVoList,
          periodDay: allData.periodDay,
          periodType: allData.periodType,
          usePeriodTime: [timestampToChange(allData.periodBeginTime, 'date'), timestampToChange(allData.periodEndTime, 'date')]
        }
        this.tableData = allData.responseServicePackageDetailVoList
      }
    },
    addSerivice () {
      const idList = []
      if (this.tableData && this.tableData.length > 0) {
        this.tableData.forEach(item => {
          idList.push(item.serviceRightId)
        })
      }
      const typeArr = []
      this.tableData.forEach(item => {
        typeArr.push(item.type)
      })
      this.$refs.addDialog.open(idList, this.type, typeArr)
    },
    cancelSerivice () {
      this.$confirm('确定删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.tableData = xor(this.tableData, this.selectData)
        this.deleteObjList = cloneDeep(this.tableData)
        this.selectData.forEach(item => {
          this.deleteObjList.push(this.deleteObj = {
            id: item.id,
            isDeleted: '1'
          })
        })
        this.$alert('删除成功')
      })
    },
    getSelectAble () {
      if (this.type === 'detail') {
        return false
      } else {
        return true
      }
    },
    getTableData (data) {
      data.forEach(item => {
        item.serviceRightId = item.id
        delete item.id
        item.servicePackageRightId = this.id
        this.tableData.push(item)
      })
    }
    // isArrSame (arr) {
    //   if (arr.length > 0) {
    //     const sameArr = []
    //     for (let i = 0; i < arr.length; i++) {
    //       let p = 0
    //       for (let j = 0; j < arr.length; j++) {
    //         if (arr[j] === arr[i]) {
    //           p++
    //         }
    //         if (p > 1 && sameArr.indexOf(arr[i]) === -1) {
    //           sameArr.push(arr[i])
    //         }
    //       }
    //     }
    //     if (sameArr.length > 0) {
    //       return false
    //     } else {
    //       return true
    //     }
    //   }
    // }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.langBox {
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 12px;
  text-align: center;
  padding: 2px 0px;
  width: 50px;
  float: left;
  margin-left: 10px;
  span {
    display: block;
    line-height: 12px;
  }
  .lang {
    border-bottom: 1px dashed #ccc;
  }
}
.dialogForm {
  .formPosition {
    position: relative;
  }
  .descSty {
    position: absolute;
    top: -152px;
    left: 115px;
  }
}

/deep/ .el-form--label-left .el-form-item__label {
  text-align: right;
  padding-right: 20px;
}

.service-table /deep/ .el-pagination {
  display: none;
}

.model-title {
  background: #e9ecf1;
  border-left: 4px solid #00b9ad;
  line-height: 40px;
  font-size: 14px;
  padding-left: 10px;
  margin-bottom: 10px;
}

// /deep/ .cell-other-style .cell {
//   display: inline-flex;
//   flex-direction: column;
//   .border-style .el-input__inner {
//     border: 1px solid red;
//   }
// }

// .validate-style {
//   color: red;
//   text-align: left;
//   padding-left: 10px;
// }

// .validate-show {
//   display: none;
// }
</style>
